import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


    public class UdpEchoServer{
        //创建一个DatagramSocket对象，后续操作网卡的基础
        private DatagramSocket socket = null;
        public UdpEchoServer(int port) throws SocketException {
            socket = new DatagramSocket(port);
            //手动指定服务器端口

            //socket = new DatagramSocket();
            // 随机分配端口
        }
        public void start() throws IOException {
            //启动服务器
            System.out.println("服务器启动！");
            while(true) {
                // 1. 读取请求并解析
                DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
                socket.receive(requestPacket);
                //当完成receive之后，数据是以二进制的形式存在储存到DatagramPacket中
                //通过转变成字符串显示出来
                String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
                // 2.根据请求计算响应
                String response = process(request);
                // 3.把响应写回到客户端
                // 创建一个响应对象，DatagramPacket往它里面构造数据，使用send返回。
                DatagramPacket responsPacket = new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());
                socket.send(responsPacket);
                // 4. 打印一个日志，把这一次数据交互打印出来
                System.out.printf("[%s:%d] req = %s, resq=%s\n",requestPacket.getAddress().toString(),
                        requestPacket.getPort(),request,response);


            }
        }
        public String process(String request) {
            return request;
        }
        public static void main(String[] args) throws IOException {
            UdpEchoServer server = new UdpEchoServer(9090);
            server.start();
        }
    }

